package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.material.model.Wlwl;
import com.liangtian.mdm.material.model.WlwlField;
import com.liangtian.mdm.material.model.WlwlTzl;
import com.liangtian.mdm.material.service.WlwlDisService;
import com.liangtian.mdm.material.service.WlwlFieldService;
import com.liangtian.mdm.material.service.WlwlService;
import com.liangtian.mdm.material.service.WlwlTzlService;
import com.liangtian.mdm.system.business.model.SysBusiness;
import com.liangtian.mdm.system.business.service.SysBusinessService;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.parameter.service.SysParameterService;
import com.liangtian.mdm.system.user.dao.SysUserDao;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.liangtian.mdm.util.StringUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wlwl")
public class WlwlController extends BaseController {
    @Autowired
    private WlwlService wlwlService;

    @Autowired
    private WlwlDisService wlwlDisService;

    @Autowired
    private WlwlTzlService wlwlTzlService;

    @Autowired
    private WlwlFieldService wlwlFieldService;

    // 日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    @Autowired
    private SysBusinessService sysBusinessService;

    // @Autowired
    // private SysFileService sysFileService;
    @Autowired
    private SysParameterService sysParameterService;
    // @Autowired
    // private SysThumbnaiDao sysThumbnaiDao;
    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @Autowired
    SysUserDao sysUserDao;

    private List<Wlwl> wlwlListByExport = null;
    private Map<String, Object> wlmap = null;


    /**
     * 根据条件查询正式物料归档数据
     *
     * @param request
     * @param wlwl
     * @return
     * @author jyh
     * @date 2016-09-26
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/queryWlwl", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryWlwl(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        String lbbms = (String) paramMap.get("lbbms");
        if (!StringUtils.isEmpty(lbbms))
            paramMap.put("lbbmArray", StringUtil.splitAsList(lbbms));
        String qcs = (String) paramMap.get("qcs");
        if (!StringUtils.isEmpty(qcs))
            paramMap.put("qcArray", spaceToList(qcs));
        String systemCode = sysParameterService.getSysParamValue("systemCode", "MDM");// 获取系统参数systemCode，如果返回值为空则默认返回值为"MDM"
        if ("WanDa".equals(systemCode)) {
            paramMap.put("wandaextr1", "true");//万达特殊需求，查询过滤92大类
        }
        PageInfo pageInfo = wlwlService.queryWlwl(paramMap);
        List<Wlwl> lst = pageInfo.getList();
        wlwlListByExport = lst;
        wlmap = paramMap;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", lst);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());//
        return jsonObject;
    }

    /**
     * 正式表物料数据归档
     *
     * @param request
     * @param wlwl
     * @return
     * @author jyh
     * @date 2016-09-26
     */
    @RequestMapping(value = "/gdWlwl", method = RequestMethod.POST)
    @ResponseBody
    public String gdWlwl(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, Object> param = RequestUtils.paramToMap(request);
            List<String> wlbms = toList((String) param.get("wlbms"));
            param.put("idArray", wlbms);
            // 获取session中用户
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            param.put("GD_UID", user.getUserId());
            param.put("GD_UNAME", user.getUserName());
            wlwlService.gdWlwl(param, wlbms);
            map.put("success", true);
            //写日志
			/*logInfo.setBusiness(Constants.WLWL);
			logInfo.setOper_type(Constants.OPER_TY);
			logInfo.setOperation("111");//111归档
			logInfo.setData_ids(toList(wlwl.getWlbm()));
			logInfo.setData_names(toList(wlwl.getWlbm()));
			SysLogUtil.insertSysLog(logInfo);*/

            SysLogUtil.insertLog("归档物料[" + wlbms + "]",
                    SysLogEnum.WL_WL.getCode(), SysLogEnum.GD.getCode(), request);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", e.getMessage());
        }
        return JSON.toJSONString(map);
    }

    /**
     * 手动下载物料到指定系统
     *
     * @return
     * @author jingyh
     * @date 2017-11-09
     */
    @RequestMapping(value = "/downWl", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject downWl(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        try {
			/*
			String wlbm = request.getParameter("wlbm");
			String jldw = request.getParameter("wllbjldw");
			if(!StringUtils.isEmpty(wlbm) && !StringUtils.isEmpty(jldw)){
				Wlwl wl = wlwlService.getWlwlByWlbm(wlbm);
//				wl.setJldw(jldw);
				String[] names = wlwlDisService.manualWlwlDis(wl);
				//super.setResult(JSONSerializer.toJSON(list));
				SysLogUtil.insertLog("分发物料["+wlbm+"]",
		        		SysLogEnum.WL_WL.getCode(), SysLogEnum.FF.getCode(), request);
				if(StringUtils.isEmpty(names)){
					jsonObject.put("success", false);
					jsonObject.put("msg", "未找到待分发的目标系统，请联系管理员！");
				}else{
					jsonObject.put("success", true);
					jsonObject.put("data", names);
				}
			}else{
				jsonObject.put("success", false);
				jsonObject.put("msg", "参数有误！");
			}*/
            //--edit by wangyk at 180519：目前前台支持批量分发，且不需要选择计量单位，选择了之前的后台代码也不使用。故将上述代码直接进行注释。
            String wlbms = request.getParameter("wlbm");
            String[] names = wlwlDisService.manualWlwlDis(wlbms);
            SysLogUtil.insertLog("分发物料[" + wlbms + "]",
                    SysLogEnum.WL_WL.getCode(), SysLogEnum.FF.getCode(), request);
            if (ArrayUtils.isEmpty(names)) {
                jsonObject.put("success", false);
                jsonObject.put("msg", "未找到待分发的目标系统，请联系管理员！");
            } else {
                jsonObject.put("success", true);
                jsonObject.put("data", names);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 传入一个ID字符串(以,号连接的),解析后,返回ID集合
     *
     * @param array
     * @return List<String>
     * @author jyh
     * @date 2016-09-27
     */
    public List<String> toList(String array) {
        ArrayList<String> list = new ArrayList<String>();
        if (array != null) {
            for (String string : array.split(",")) {
                list.add(string);
            }
        }
        return list;
    }

    /**
     * 获取正式表物料数据(冻结、解冻)
     *
     * @param request
     * @param wlwl
     * @return
     * @author ly
     * @date 2016-12-15
     */
    @ResponseBody
    @RequestMapping(value = "/getWlwlListByCond", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlwlListByCond(HttpServletRequest request, Wlwl wlwl) {
        Map paramMap = RequestUtils.paramToMap(request, Wlwl.class, false);
        PageInfo pageInfo = wlwlService.queryWlwl(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @RequestMapping(value = "/view", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject view(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String wlbm = request.getParameter("wlbm");
        if (!StringUtils.isEmpty(wlbm)) {
            Wlwl wlwl = wlwlService.getWlwlByWlbm(wlbm);
            Map<String, Object> cond = new HashMap<>();
            cond.put("wlbm", wlbm);
            List<WlwlTzl> tzlList = wlwlTzlService.getWlwlTzl(cond);
            jsonObject.put("wlwl", wlwl);
            jsonObject.put("tzlList", tzlList);
            //可配置物料字段
            Map<String, Object> field_cond = new HashMap<>();
            field_cond.put("sfbdxs", "1");
            List<WlwlField> fieldList = wlwlFieldService.queryWlwlFieldByCond(field_cond);
            jsonObject.put("fieldList", fieldList);
            //附件信息
            SysBusiness sysb = new SysBusiness();
            sysb.setBusTable("WL_WL");
            sysb.setLimit("20");//由于调用分页方法，该属性需要有值
            List<SysBusiness> bList = sysBusinessService.queryBusByContion(sysb).getList();//查询业务类型
            String bus_id = bList.get(0).getBusId();//业务类型
            Map<String, Object> param = new HashMap<>();
            param.put("dataId", wlwl.getWlDrId());
            param.put("surveyType", bus_id);
            //附件
            // List<SysFile> files = sysFileService.queryFileBySurvey(param);
            // if (!StringUtils.isEmpty(files))
            //     jsonObject.put("files", files);
            //
            // //缩略图
            // List<SysThumbnai> thumbnais = sysThumbnaiDao.querySysThumbnaiByCond(param);
            // if (!StringUtils.isEmpty(thumbnais))
            //     jsonObject.put("thumbnais", thumbnais);
        }
        return jsonObject;
    }

    public static List<String> spaceToList(String array) {
        ArrayList<String> list = new ArrayList<String>();
        if (array != null) {
            for (String string : array.split(" ")) {
                list.add(string);
            }
        }
        return list;
    }

    /**
     * 根据条件查询物料审核数据
     *
     * @param request
     * @param wlwl
     * @return
     * @author ly
     * @date 2018-01-25
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/queryWlwlApprove", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryWlwlApprove(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        String lbbms = (String) paramMap.get("lbbms");
        if (!StringUtils.isEmpty(lbbms))
            paramMap.put("lbbmArray", StringUtil.splitAsList(lbbms));
        String qcs = (String) paramMap.get("qcs");
        if (!StringUtils.isEmpty(qcs))
            paramMap.put("qcArray", spaceToList(qcs));
        String systemCode = sysParameterService.getSysParamValue("systemCode", "MDM");// 获取系统参数systemCode，如果返回值为空则默认返回值为"MDM"
        if ("WanDa".equals(systemCode)) {
            paramMap.put("wandaextr1", "true");//万达特殊需求，查询过滤92大类
        }
        String approveUser = (String) paramMap.get("approve_user");
        if (!StringUtils.isEmpty(approveUser)) {
            Map<String, Object> param = new HashMap<>();
            param.put("userName", approveUser);
            SysUser user = sysUserDao.mobileCheckLogin(param);
            paramMap.put("approve_user", user.getUserId());
        }
        PageInfo pageInfo = wlwlService.queryWlwlByApprove(paramMap);
        List<Wlwl> lst = pageInfo.getList();

        PageInfo pageInfo2 = wlwlService.queryWlwlUpdByApprove(paramMap);
        List<Wlwl> lst2 = pageInfo2.getList();
        lst.addAll(lst2);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", lst);// JSONArray
        jsonObject.put("total", pageInfo.getTotal() + pageInfo2.getTotal());//
        return jsonObject;
    }

    /**
     * 导出当前页数据
     *
     * @param request
     * @return
     
     * @date 2018-01-31
     */
    @RequestMapping(value = "wlwlExportExcel", method = RequestMethod.POST)
    @ResponseBody
    public String wlwlExportExcel(HttpServletResponse response, HttpServletRequest request) {
        //查询是否表单显示的配置字段
        List<WlwlField> fieldList = this.getWlwlFieldsByLb();
        if (wlwlListByExport.size() > 0 && wlwlListByExport != null) {
            wlwlService.exportWlwl(wlwlListByExport, fieldList, response);
        }
        return null;
    }

    /**
     * 导出所有数据
     *
     * @param pageNum
     * @param limit
     * @return
     
     * @date 2018-01-31
     */
    @RequestMapping(value = "wlwlExportExcel2", method = RequestMethod.POST)
    @ResponseBody
    public String wlwlExportExcel2(HttpServletResponse response, HttpServletRequest request) {
        String start = request.getParameter("Second_PageHelper");
        String end = request.getParameter("First_PageHelper");
        //查询是否表单显示的配置字段
        List<WlwlField> fieldList = this.getWlwlFieldsByLb();
        if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
            wlmap.put("pageNum", start);
            wlmap.put("limit", end);
            PageInfo pageInfo = wlwlService.queryWlwl2(wlmap);
            List l = pageInfo.getList();
            if (l.size() > 0 && l != null) {
                wlwlService.exportWlwl(l, fieldList, response);
            }
        }
        return null;
    }

    public List<WlwlField> getWlwlFieldsByLb() {
        // 可配置物料字段
        Map<String, Object> field_cond = new HashMap<>();
        field_cond.put("sflbxs", "1");
        List<WlwlField> fieldList = wlwlFieldService.queryWlwlFieldByCond(field_cond);
        return fieldList;
    }


    /**
     * 晋煤 添加物料启用系统标识
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateFiled", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateFiled(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 0);
        String field1 = request.getParameter("field1");
        String wlbm = request.getParameter("wlbm");
        if (!StringUtils.isEmpty(field1) && !StringUtils.isEmpty(wlbm)) {
            Map<String, Object> cond = new HashMap<>();
            cond.put("field1", field1);
            cond.put("wlbm", wlbm);
            wlwlService.updateWlwlFiled(cond);

            jsonObject.put("status", 1);
            jsonObject.put("field1", field1);
        }
        return jsonObject;
    }

}

